#!/usr/bin/env python
# -*- coding: utf-8 -*-

from django.shortcuts import get_object_or_404
from django.views.generic import ListView
from hony.models import ArticleModels, SeriesModel, StationModel, AuthorModel

class BaseListView(ListView):
    template_name = "article_list.html"
    paginate_by = 20
    title = None
    summary = None
    keyword = None

    def get_context_data(self, object_list=None, *arges, **kwargs):
        context = super().get_context_data(object_list=object_list, *arges, **kwargs)
        context["title"] = self.get_title()
        context["summary"] = self.get_summary()
        context["keyword"] = self.get_keyword()
        context["stations"] = StationModel.objects.filter(enabled=True)
        context["crumbs"] = self.get_crumbs()
        return context
    
    def get_title(self):
        if self.title:
            return self.title
        return ""

    def get_summary(self):
        if self.summary:
            return self.summary
        return ""

    def get_keyword(self):
        if self.summary:
            return self.summary
        return ""

    def get_crumbs(self):
        crumbs = []
        if hasattr(self, "station"):
            crumbs.append(self.station)
        elif self.kwargs.get("station"):
            crumbs.append(get_object_or_404(StationModel, id=int(self.kwargs["station"])))
        if hasattr(self, "series"):
            crumbs.append(self.series)
        elif self.kwargs.get("series"):
            crumbs.append(get_object_or_404(SeriesModel, id=int(self.kwargs["series"])))
        return crumbs 



class ArticleListView(BaseListView):
    queryset = ArticleModels.objects.filter(enabled=True)
    title = "宇宙洪荒"
    summary = "天地玄黄, 日月盈仄"
    keyword = ""

    def get_queryset(self):
        queryset = super().get_queryset() 
        if self.kwargs.get("station"):
            self.station = get_object_or_404(StationModel, id=int(self.kwargs["station"]))
            queryset = queryset.filter(station_id=self.station.id)
        if self.kwargs.get("series"):
            self.series = get_object_or_404(SeriesModel, id=int(self.kwargs["series"]))
            queryset = queryset.filter(series_id=self.series.id) return queryset.order_by("series", "series_sort")

class ArticleSeriesListView(ArticleListView):
    def get_queryset(self):
        return super().get_queryset().filter(series_id=self.request.series)

class ArticleStationListView(ArticleListView):
    def get_queryset(self):
        return super().get_queryset().filter(station_id=self.request.station)
       
class SeriesListView(BaseListView):
    queryset = SeriesModel.objects.filter(enabled=True)

class StationListView(BaseListView):
    queryset = StationModel.objects.filter(enabled=True)

